package com.ev.framework.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 * @author 顾明杰
 * 定时任务配置类，目前定时任务通过保存任务进入数据库实现
 * @see quartz.properties
 * @see com.ev.framework.config.JobFactory
 */
@Configuration
public class QuartzConfiguration {
	
	@Autowired
	private JobFactory jobFactory;
	
	@Autowired
	private DataSource dataSource;    // 如果使用application.properties中的数据源可以用这种方式
	
	@Bean
	public SchedulerFactoryBean myScheduler() throws IOException {
		SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
		schedulerFactoryBean.setDataSource(dataSource);                  // 使用 application.properties 中的数据源
		schedulerFactoryBean.setOverwriteExistingJobs(true);
		schedulerFactoryBean.setJobFactory(jobFactory);
		schedulerFactoryBean.setQuartzProperties(quartzProperties());    // 使用 quartz.properties 中的数据源
		schedulerFactoryBean.setSchedulerName("myScheduler");
		schedulerFactoryBean.setStartupDelay(1);// 延迟两秒启动
		schedulerFactoryBean.setAutoStartup(true);
		return schedulerFactoryBean;
	}

	/*@Bean
	public SchedulerFactoryBean myScheduler2() throws IOException {
		SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
		schedulerFactoryBean.setDataSource(dataSource);                   // 使用 application.properties 中的数据源
		schedulerFactoryBean.setOverwriteExistingJobs(true);
		schedulerFactoryBean.setJobFactory(jobFactory);
		schedulerFactoryBean.setQuartzProperties(quartzProperties());  // 使用 quartz.properties 中的数据源
		schedulerFactoryBean.setSchedulerName("myScheduler2");
		schedulerFactoryBean.setStartupDelay(2);// 延迟两秒启动
		schedulerFactoryBean.setAutoStartup(true);
		return schedulerFactoryBean;
	}*/
	
	private Properties quartzProperties() throws IOException {
		PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
		propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
		propertiesFactoryBean.afterPropertiesSet();
		return propertiesFactoryBean.getObject();
	}
}